/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { forwardRef, useState, useCallback } from 'react';
import { Input, Row, Col, Button, Icon, Popover } from 'antd';
import styles from './styles.less';

const infoContent = (
  <div style={{ width: 300 }}>
    <div>维护多个关键字用“、”隔开，</div>
    <div>例如：北京、上海</div>
    <div>维护组合关键字用“+”连接</div>
    <div>例如：北京+海淀</div>
    <div>
      当关键字为
      <span className={styles.red}>北京+海淀、上海</span>
      时，表示收件地址内包含关键字
      <span className={styles.red}>北京</span>和<span className={styles.red}>海淀</span>
      时对应该格口，或者包含
      <span className={styles.red}>上海</span>
      时对应格口
    </div>
  </div>
);

const KeyWordsInput = forwardRef((props, ref) => {
  const { value = [], onChange } = props;

  const [inputKeyWord, setInputKeyWord] = useState([]);
  const [inputValue, setInputValue] = useState();

  const onAdd = useCallback(
    () => {
      const arr = [...value, ...inputKeyWord];
      if (inputKeyWord.length > 0) {
        onChange && onChange(arr);
        setInputValue('');
        setInputKeyWord([]);
      }
    },
    [onChange, value, inputKeyWord],
  );

  const onBlur = useCallback(e => {
    e.persist();
    const { value: inputVal } = e.target;
    if (inputVal) {
      setInputKeyWord(inputVal.split('、').filter(i => i));
    } else {
      setInputKeyWord([]);
    }
  }, []);

  const onDelete = useCallback(
    index => {
      value.splice(index, 1);
      onChange && onChange(value);
    },
    [value, onChange],
  );

  const onInputChange = useCallback(e => {
    e.persist();
    const { value: inputVal } = e.target;
    setInputValue(inputVal.replace(/\s+/g, ''));
    if (!inputVal) {
      setInputKeyWord([]);
    }
  }, []);

  return (
    <Row type="flex">
      <Col span={24}>
        <Row type="flex" gutter={[10]}>
          <Col style={{ flex: 1 }}>
            <Input
              allowClear
              value={inputValue}
              onChange={onInputChange}
              onBlur={onBlur}
              placeholder="请输入该格口对应的收件地址内关键字"
            />
          </Col>
          <Col>
            <Button onClick={onAdd} size="small" type="primary">
              添加
            </Button>
          </Col>
          <Col>
            <Popover content={infoContent}>
              <Icon style={{ cursor: 'pointer' }} type="question-circle" />
            </Popover>
          </Col>
        </Row>
      </Col>
      <Col span={24} className={styles.keyWordsOld}>
        <Row type="flex">
          {value.map((keyWord, i) => (
            <Col key={i} className={styles.keyWord}>
              <div>{keyWord}</div>
              <Icon onClick={() => onDelete(i)} type="close-circle" />
            </Col>
          ))}
        </Row>
      </Col>
    </Row>
  );
});

export default KeyWordsInput;
